#!/bin/bash

# Copyright 2016--2018 Jan Pazdziora
#
# Licensed under the Apache License, Version 2.0 (the "License").

# Prepare HBAC rules for services webapp and idp, and OTPs for IPA clients.

set -e

exec >> /var/log/ipa-server-run.log 2>&1

if ! [ -f /data/allow_all_disabled ] ; then
	kinit admin < /data/admin-password
	(
	set -x
	ipa hbacsvc-find webapp || ipa hbacsvc-add webapp
	ipa hbacrule-find allow_webapp || (
		ipa hbacrule-add allow_webapp --usercat=all --hostcat=all --desc='Allow access to webapp service.'
		ipa hbacrule-add-service allow_webapp --hbacsvcs=webapp
	)

	ipa hbacsvc-find idp || ipa hbacsvc-add idp
	ipa hbacrule-find allow_idp || (
		ipa hbacrule-add allow_idp --usercat=all --desc='Allow access to idp service.'
		ipa hbacrule-add-service allow_idp --hbacsvcs=idp
		ipa hbacrule-disable allow_all
	)

	ipa hbacrule-disable allow_all

	touch /data/allow_all_disabled
	)
fi

HOSTS="idp.example.test www.example.test client.example.test"
for i in $HOSTS ; do
	if ! [ -f /data/$i-otp ] ; then
		echo "Creating host record for $i"
		klist > /dev/null || kinit admin < /data/admin-password
		(
		set -x
		ipa host-find $i > /dev/null && ipa host-del $i
		ipa host-add --random $i --force --raw | awk '/randompassword:/ { print $2 }' > /data/$i-otp.1
		ipa service-add --force HTTP/$i
		mv /data/$i-otp.1 /data/$i-otp
		)
	fi
done

ipa hbacrule-add-host allow_idp --hosts=idp.example.test || :

kdestroy -A
